package cn.yunyichina.provider.message.thread;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;
import cn.yunyichina.provider.iface.entity.PersonalUser;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.message.dao.MessageHistoryDao;
import cn.yunyichina.provider.message.dao.OrgAppTemplateDao;
import cn.yunyichina.provider.message.dao.TmpTemplateDao;
import cn.yunyichina.provider.message.dao.TmpTemplateListDao;
import cn.yunyichina.provider.message.entity.MessageHistory;
import cn.yunyichina.provider.message.entity.OrgAppTemplate;
import cn.yunyichina.provider.message.entity.TmpTemplate;
import cn.yunyichina.provider.message.entity.TmpTemplateList;
import cn.yunyichina.provider.message.sdk.app.JpushMessage;
import cn.yunyichina.provider.message.service.impl.MsgServiceImpl;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.IDUtils;
import cn.yunyichina.utils.convert.JsonUtils;


public class MsgAppPushRunnable implements Runnable {
	private static Logger logger = LoggerFactory.getLogger(MsgAppPushRunnable.class);

	private TmpTemplateDao tmpTemplateDao = SpringContextHandler.getBean(TmpTemplateDao.class);
	private OrgAppTemplateDao orgAppTemplateDao = SpringContextHandler.getBean(OrgAppTemplateDao.class);
	private TmpTemplateListDao tmpTemplateListDao = SpringContextHandler.getBean(TmpTemplateListDao.class);
	private MessageHistoryDao messageHistoryDao = SpringContextHandler.getBean(MessageHistoryDao.class);

	private String strJsonMessage;


	private Map<String, Object> paramMap;


	public MsgAppPushRunnable(String strJsonMessage) {
		this.strJsonMessage = strJsonMessage;
	}


	@Override
	public void run() {
		MessageHistory messageHistory = new MessageHistory();
		String userId = null;
		try {
			if (logger.isDebugEnabled()) {
				logger.debug("app消息发送入口:{}",strJsonMessage);
			}
			JSONObject param = JsonUtils.parseObject(strJsonMessage);
			
			String orgCode = param.containsKey("org_code") ? param.getString("org_code") : "";
			
			userId = param.getString("to_user");
			String templateCode = param.getString("template_code");
			
			messageHistory.setId(IDUtils.getUUID32());
			messageHistory.setOrgCode(orgCode);
			messageHistory.setUserId(userId);
			messageHistory.setLibraryTemplateCode(templateCode);
			messageHistory.setIsRead( (short) 1);
			messageHistory.setCreatedTime(DateUtils.dateToString(new Date()));
			messageHistory.setCreatedBy(userId);
			
			JSONObject paramMap = JsonUtils.parseObject(param.get("msg_content"));
			logger.debug("msg_content_jsonObject:"+paramMap+",user_id="+userId);
			
			//查找消息模板
			TmpTemplate tmpTemplate = getTmpTemplate(param.getString("template_code"),param.getString("org_app_code"),orgCode);
			
			if (StringUtils.isBlank(param.getString("url"))) {
				param.put("url",tmpTemplate.getUrl());
			}
			param.put("url",MsgServiceImpl.parseUrl(param.getString("url"),param));

			if (tmpTemplate.getListTmpTemplateList() != null && tmpTemplate.getListTmpTemplateList().size() > 0) {
				for (TmpTemplateList tmpTemplateList : tmpTemplate.getListTmpTemplateList()) {
					for (String key : paramMap.keySet()) {
						tmpTemplateList.setValue(tmpTemplateList.getValue().replaceAll("(?i)%" + key + "%",
								Matcher.quoteReplacement(String.valueOf(paramMap.get(key)))));
					}
				}
			}

			String templateJson = JSON.toJSONString(tmpTemplate);
			logger.debug("templateJson:"+templateJson+",user_id="+userId);
			
			Org org = BaseService.getBaseClient().getOrgByCode(orgCode);
			logger.debug("org:"+JsonUtils.toJsonString(org)+",user_id="+userId);
			
			messageHistory.setOrgId(org.getId());
			messageHistory.setOrgName(org.getOrgName());
			
			messageHistory.setMsgTitle(tmpTemplate.getTemplateTitle());
			messageHistory.setMsgContent(templateJson);
			
			//获取用户名
			Map<String,String> mapUser = new HashMap<>();
			mapUser.put("id", userId);
			
			List<PersonalUser> listPersonalUser = BaseService.listPersonalUser(JsonUtils.toJsonString(mapUser));
			logger.debug("listPersonalUser:"+JsonUtils.toJsonString(listPersonalUser)+",user_id="+userId);
			if (listPersonalUser != null && listPersonalUser.size() == 1) {
				messageHistory.setUserName(listPersonalUser.get(0).getUserName());
			}
			
			JSONObject jsonObject = JpushMessage.sendPush(userId,"",tmpTemplate.getTemplateTitle());
			if (logger.isDebugEnabled()) {
				logger.debug("app消息发送结果: {}", new Object[] {jsonObject }+",user_id="+userId);
			}

			if (logger.isDebugEnabled()) {
				logger.debug("app消息发送结束.................."+",user_id="+userId);
			}
		} catch (Exception e) {
			logger.error("发送app消息异常（线程）："+e.toString()+",user_id="+userId);
			logger.error(ErrorCodeDefine.getStackTrace(e)+",user_id="+userId);
			
		}
		finally {
			try {
				logger.debug("messageHistory:"+JsonUtils.toJsonString(messageHistory));
				messageHistoryDao.insert(messageHistory);
			}
			catch (Exception ex) {
				logger.error("记录APP历史异常："+ErrorCodeDefine.getStackTrace(ex));
			}
		}
	}

	private TmpTemplate getTmpTemplate(String templateCode,String appCode,String orgCode) {
		logger.debug("getTmpTemplate:templateCode={},appCode={},orgCode={}",templateCode,appCode,orgCode);

		OrgAppTemplate orgAppTemplate = orgAppTemplateDao.selectForMatch(templateCode, appCode, orgCode,1,3);
		if (orgAppTemplate == null ) {
			logger.error( "找不到模板模板编码("+templateCode+")");
			throw new CallException(ErrorCodeDefine.MESSAGE_PARAM, "找不到模板模板编码("+templateCode+")");
		} 
		
		TmpTemplate tmpTemplate = new TmpTemplate();
		tmpTemplate.setTemplateCode(orgAppTemplate.getLibraryTemplateCode());
		List<TmpTemplate> listTmpTemplate = tmpTemplateDao.select(tmpTemplate);
		if (listTmpTemplate == null || listTmpTemplate.size() == 0) {
			logger.error("找不到模板内部模板编码("+templateCode+")");
			throw new CallException(ErrorCodeDefine.MESSAGE_PARAM, "找不到模板内部模板编码("+templateCode+")");
		}
		
		tmpTemplate = listTmpTemplate.get(0);
		TmpTemplateList tmpTemplateList = new TmpTemplateList();
		tmpTemplateList.setTmpTemplateCode(tmpTemplate.getTemplateCode());
		List<TmpTemplateList> listTmpTemplateList = tmpTemplateListDao.select(tmpTemplateList);
		tmpTemplate.setListTmpTemplateList(listTmpTemplateList);
		
		logger.debug("获取的tmpTemplate："+JsonUtils.toJsonString(tmpTemplate));
		return listTmpTemplate.get(0);
	}
}
